package org.sxm.cloud.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.sxm.cloud.dao.ProductDao;
import org.sxm.cloud.entity.product.ProductEntity;
import org.sxm.cloud.exception.BizException;
import org.sxm.cloud.service.IProductService;

import javax.annotation.Resource;
import java.util.Objects;

@Service("productService")
public class ProductService implements IProductService {

    @Resource
    private ProductDao productRepository;

    private final static Logger log = LoggerFactory.getLogger(ProductService.class);

    @Override
    public ProductEntity getByProductId(Integer productId) {
        if(productId <= 0){
            throw new BizException("查询产品不存在");
        }
        ProductEntity product = productRepository.findById(productId).orElse(null);
        return product;
    }

    @Override
    public int reduceProduct(Integer productId, Integer num) {
        ProductEntity product = this.getByProductId(productId);
        if (Objects.isNull(product)) {
            throw new BizException("扣减产品库存，产品不存在");
        }
        if(product.getNum() < num.intValue()){
            throw new BizException("产品库存不足");
        }
        product.setNum(product.getNum()-num);
        productRepository.save(product);
        log.info("产品{}，扣减产品数量{}", product, num);
        return 1;
    }
}
